# -*- coding:utf-8 -*-
__author__ = "daoyu"
__date__ = "2023-6-29"
__doc__ = "定义全局函数"

import pytest
import requests
from jsonpath import jsonpath
import os,sys
sys.path.append(os.getcwd())
from utils.logger_client import logger
from utils.mail_client import YagMail

@pytest.fixture()
def get_token():
    """
        获取token
    """
    url = "http://119.45.233.102:2233/testgoup/system/login"
    data = '{"username": "wugy", "password": "e10adc3949ba59abbe56e057f20f883e"}'
    res = requests.request("post", url=url, json=eval(data))
    return jsonpath(res.json(), "$..token")[0]

def pytest_collection_modifyitems(items):
    """
        测试用例收集完成时，将收集到的item的name和nodeid编码格式改为"utf-8"
    """
    for item in items:
        item.name = item.name.encode("utf-8").decode("unicode_escape")
        item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")

@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
    """
        每条用例执行后，生成结果日志
        对于每一条测试用例(item)的每个执行阶段(call)，返回一个测试报告对象(_pytest.runner.TestReport)
    """
    # 获取常规钩子函数的调用结果，返回给result对象。
    result = yield
    # 获取调用结果的测试报告，返回给report对象。
    # 该对象包括when(setup, call, teardown)，nodeid(测试用例名称)，outcome(测试用例执行结果：passed, failed)，location(测试用例位置信息及名称)，longrepr(异常时详细信息)，duration(用例耗时)
    # item对象(测试用例Function 及名称)，item.functiom.doc(测试用例函数的描述)，call.excinfo(异常信息)
    report = result.get_result()
    # 定义用例结果变量
    if "pass_case" not in globals():
        globals()["pass_case"] = []
    if "fail_case" not in globals():
        globals()["fail_case"] = []
    # 记录测试结果日志，收集用例结果
    if report.when == "call" and report.outcome == "passed":
        globals()["pass_case"].append(report.location[2])
        logger.success(f"执行测试用例{report.location[2]}成功")
    elif report.when == "call" and report.outcome == "failed":
        globals()["fail_case"].append(report.location[2])
        logger.error(f"执行测试用例{report.location[2]}失败，日志如下：\
                     \n{call.excinfo}")

@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """
        输出测试报告
    """
    logger.info("开始处理测试报告")
    yield
    if len(globals()['fail_case']) > 0:
        contents = f"测试结果如下：\
                    \n {len(globals()['pass_case'])}条用例执行成功\
                    \n {len(globals()['fail_case'])}条用例执行失败\
                    \n 测试失败的用例如下：\
                    \n {globals()['fail_case']}"
        YagMail().send(contents=contents)
    else:
        logger.info("用例全部执行成功，无需发送邮件")